package com.amgl.mobike.widget.loadmore;

import android.support.annotation.IntDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * 加载更多，RecyclerView.AddOnScrollListener
 * Created by 阿木 on 2016/12/26.
 */
public class ScrollToLoadMoreListener extends ScrollToLastItemListener {
    public static final int STATE_IDLE = 0;
    public static final int STATE_LOADING = 1;
    public static final int STATE_END = 2;
//    public static final int STATE_ERROR = 3;

    public ScrollToLoadMoreListener(LoadMoreListener loadMoreListener) {
        mLoadMoreListener = loadMoreListener;
    }

    private LoadMoreListener mLoadMoreListener;
    private int mLoadingState = STATE_IDLE;

//    private ILoadMoreView mLoadingView;
//
//    public void setLoadingView(ILoadMoreView loadingView) {
//        mLoadingView = loadingView;
//        setLoadingState(mLoadingState);
//    }

    /**
     * IDLE时可以加载更多。
     * End表示没有更多数据。
     * Loading状态自动设置。
     *
     * @param loadingState
     */
    public void setLoadingState(@LoadingState int loadingState) {
        mLoadingState = loadingState;
//        if (mLoadingView != null) {
//            if (mLoadingState == STATE_IDLE) {
//                mLoadingView.showIdleView();
//            } else if (loadingState == STATE_LOADING) {
//                mLoadingView.showLoadingView();
//            } else if (loadingState == STATE_END) {
//                mLoadingView.showEndView();
//            }
//        }
    }

    /**
     * 加载更多完成
     *
     * @param hasModeData 是否有更多数据
     */
    public void loadComplete(boolean hasModeData) {
        if (hasModeData) {
            setLoadingState(STATE_IDLE);
        } else {
            setLoadingState(STATE_END);
        }
    }

    @Override
    protected void onScrollToLast(int lastVisiblePosition) {
        if (mLoadMoreListener == null)
            return;
        if (mLoadingState == STATE_IDLE && mLoadMoreListener.canLoadMore(lastVisiblePosition)) {
            setLoadingState(STATE_LOADING);
            mLoadMoreListener.loadMore();
        }
    }

    @IntDef({STATE_IDLE, STATE_LOADING, STATE_END})
    @Retention(RetentionPolicy.SOURCE)
    private @interface LoadingState {
    }

    public interface LoadMoreListener {

        /**
         * 执行加载更多
         */
        void loadMore();

        /**
         * 是否可以加载更多
         *
         * @param lastItemPosition 最后一个item
         * @return
         */
        boolean canLoadMore(int lastItemPosition);
    }
}
